<template>
  <el-row>
    <el-upload
      class="avatar-uploader"
      action="http://localhost:8080/"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload">
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    <el-button @click="upLoad">
    上传轮播图
    </el-button>
  </el-row>
</template>
<script>
import axios from 'axios'
import { requestCommon, ERR_OK } from '@/api/api.js'
export default {
  props: {
    id: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      imageUrl: '',
      file: {},
      huser_id: 0
    }
  },
  created() {},
  methods: {
    upLoad() {
      if (!this.imageUrl) {
        this.$notify({
          title: '提示',
          message: '请先添加缩略图！',
          position: 'top-left'
        })
        return false
      }
      const url = 'api/carmation/addPic.html'
      const param = {
        pic: this.imageUrl,
        pic_name: this.file.name,
        mation_id: this.id === 0 ? '' : this.id
      }
      requestCommon(url, param)
        .then(res => {
          if (res.code === ERR_OK) {
            this.$notify({
              title: '成功',
              message: res.message,
              position: 'top-left'
            })
            this.$emit('picUrl', res.data.imgPath)
          } else {
            this.$notify({
              title: '失败',
              message: res.message,
              position: 'top-left'
            })
          }
        })
        .catch(e => {
          console.log(e)
        })
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      let that = this
      const isJPG = file.type === 'image/jpeg'
      const isLt = file.size / 1024 / 1024 < 0.5
      var reader = new FileReader()
      this.file = file
      reader.readAsDataURL(file)
      reader.onload = function() {
        //读取完成后，数据保存在对象的result属性中
        that.imageUrl = this.result
      }

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt) {
        this.$message.error('上传头像图片大小不能超过 0.5MB!')
      }
      return false
    }
  }
}
</script>
<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 200px;
  height: 200px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
